import React, { useState } from 'react';
import { connect } from 'dva';
import { Row, Card, Button, Form, Select, Checkbox, Input, message } from 'antd';
import { findDicByCodeSort } from '@/support/common';
import { routerRedux } from 'dva/router';

const { Option } = Select;
const { TextArea } = Input;
const CheckboxGroup = Checkbox.Group;

const layout = {
  width: 400,
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const mapStateToProps = (state: any) => ({
  listData: state?.chargingLimitConfig?.pageData,
  loading: state.loading.effects['chargingLimitConfig/getFetchPage'],
  dicData: state?.menu?.dicData,
  userProfile: state?.menu?.userProfile,
});

const chargingLimitDetail: React.FC = props => {
  const {
    dispatch,
    dicData,
    userProfile,
    location: { state = {} },
  } = props;
  const { formData, isEdit } = state;
  const operator = userProfile.accountName;
  const lowerLimitOptions = findDicByCodeSort(dicData, 'chargingLowerLimitSOC')

  const currentLimitOptions = findDicByCodeSort(dicData, 'chargingCurrentLimit').map((d: any) => ({ label: d.dictValue, value: d.dictKey  }))
  const [brandOptions, setBrandOptions] = useState([])
  const [seriesOptions, setSeriesOptions] = useState([])
  const [groupOptions, setGroupOptions] = useState([])
  const initialValues = {
    brandCode: formData.brandCode
  }
  const [form] = Form.useForm();
  
  const goBack = () => {
    sessionStorage.setItem('chargingLimitConfigBrand', initialValues.brandCode)
    dispatch(routerRedux.push({ pathname: '/remoteConfiguration/chargingLimitConfig' }));
  };

  const handleFormReset = () => {
    form.resetFields();
  }

  const getBrandOptions = () => {
    dispatch({
      type: 'basedata/brandFetch',
      callback: (res) => {
        const data = res.data;
        setBrandOptions(data.map((item: { brandCode: any; brandName: any }) => {
          return {
            value: item.brandCode,
            label: item.brandName,
          };
        }))
      },
    });
  }

  const getSeriesOptions = (brandId: string) => {
    dispatch({
      type: 'http/getFetchPage',
      payload: {
        url: '/msdevice/base/vehicle/series/bybrand/list',
        brandId 
      },
      callback: (res: any) => {
        const data = res.data;
        setSeriesOptions(data.map((item: { seriesCode: any; seriesName: any }) => {
          return {
            value: item.seriesCode,
            label: item.seriesName,
          };
        }))
      }
    })
  }

  const getGroupOptions = (seriesCode: string) => {
    dispatch({
      type: 'http/postData',
      payload: {
        url: '/vehicle/group/findBySeriesCode',
        seriesCode,
      },
      callback: (res: any) => {
        const data = res.data;
        setGroupOptions(data.map((item: any) => {
          return {
            value: item.code,
            label: item.name,
          };
        }))
      }
    })
  }

  React.useEffect(() => {
    getBrandOptions()
    getSeriesOptions(formData?.brandCode)
    if (isEdit) {
      getGroupOptions(formData?.seriesCode)
    }
    form.setFieldsValue({...formData})
  }, [])

  const handleSeriesChange = (val: string) => {
    setGroupOptions([])
    form.setFieldsValue({groupCode: ''})
    getGroupOptions(val)
  }

  const onFinish = (formData: any) => {
    const postData = {
      ...formData,
      operationType: isEdit ? 'UPDATE' : 'ADD'
    }
    dispatch({
      type: 'chargingLimitConfig/postObj',
      payload: {
        url: '/msrcs/chargingLimitConfig/toConfigure',
        ...postData,
        operator,
      },
      callback: res => {
        if (res.statusCode === '0') {
          message.success('操作成功');
          goBack();
        }
      },
    });
  }

  return (
    <Card>
      <Form
        {...layout}
        initialValues={initialValues}
        form={form}
        name="control-hooks"
        onFinish={onFinish}
        style={{ width: 600 }}
      >
        <Form.Item name="brandCode" label="品牌" rules={[{ required: true, message: '品牌为必填项' }]}>
          <Select placeholder="请选择" disabled>
            {brandOptions.map((option: any, index: number) => (
              <Option value={option.value} key={index}>{option.label}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="seriesCode" label="车系" rules={[{ required: true, message: '请选择车系' }]}>
          <Select placeholder="请选择" onChange={handleSeriesChange}>
            {seriesOptions.map((option: any, index: number) => (
              <Option value={option.value} key={index}>{option.label}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="groupCode" label="车型组" rules={[{ required: true, message: '请选择车型组' }]}>
          <Select placeholder="请选择">
            {groupOptions.map((option: any, index: number) => (
              <Option value={option.value} key={index}>{option.label}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="socLowerLimit" label="充电soc下限" rules={[]}>
          <Select placeholder="请选择">
            {lowerLimitOptions.map((option: any, index: number) => (
              <Option value={option.dictKey} key={index}>{option.dictValue}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="currentLimit" label="慢充电流限值" rules={[]}>
          <CheckboxGroup options={currentLimitOptions} />
        </Form.Item>
        <Form.Item name="remark" label="备注" rules={[
          /* {
            validator: (_, text) => {
              if (text.length > 100) {
                return Promise.reject('备注长度限制100个字符');
              }
              return Promise.resolve();
            },
          } */
        ]}>
          <Input placeholder="请输入备注" maxLength={100} />
        </Form.Item>
        <Form.Item>
          <Row justify="end">
            <Button key="confirm" style={{ marginRight: 12 }} type="primary" htmlType="submit">
              确定
            </Button>
            <Button key="reset" style={{ marginRight: 12 }} htmlType="button" onClick={handleFormReset}>
              重置
            </Button>
            <Button key="cancel" htmlType="button" onClick={goBack}>
              取消
            </Button>
          </Row>
        </Form.Item>
      </Form>
    </Card>
  )
}

export default connect(mapStateToProps)(chargingLimitDetail);
